import json
import time
import requests
import allure
import urllib3
from common.read_yaml import get_yaml_filepath
from common.read_config import env
from urllib.parse import urlencode


data = get_yaml_filepath(Environ='data.yaml')
class HttpClient:
    def __init__(self):
        self.host = data['admin_host']

    default_header = {"Content-Type":"application/json"}

    def send(self,url,method,headers={},body={},token={},sessions={}):
        """
        :param url:
        :param method:
        :param headers:
        :param body:
        :param token:
        :param sessions:
        :return:
        """
        global result
        headers.update(self.default_header)

        if token:
            headers['authorization'] = token
        if sessions:
            headers['authorization'] = sessions

        if method == 'get':
            result = requests.get(url,params=body,headers=headers)
            self.creat_request_log(url,method,body,headers)
            self.creat_response_log(result.status_code, result.text)
        elif method == 'post':
            result = requests.post(url,data=json.dumps(body),headers=headers,allow_redirects=False)  # 取消重定向
            self.creat_request_log(url,method,body,headers)
            self.creat_response_log(result.status_code, result.text)
        elif method == 'patch':
            result = requests.post(url, data=json.dumps(body), headers=headers)

        try:
            return result.json()
        except:
            return result.content  # 针对重定向请求特殊处理，否则json转换报错

    def get_full_url(self,url,etc = {},replace = {},h = ""):
        """

        :param url:
        :param etc: url中可拼接的参数
        :param replace: 动态替换数据
        :param h: 默认删除空格
        :return:
        """

        if h:
            host = h.rstrip('/')  # rstrip 删除string 字符串末尾的指定字符（默认空格）
        else:
            host = self.host.rstrip()

        url = url.lstrip('/')  # lstrip 用于截掉字符串左边的空格或者指定字符
        full_url = host + "/" + url
        # full_url += "?platform={}&time=".format(env) + str(int(time.time()*1000))

        if etc:
            s = urlencode(etc)  # urlencode 可以把key-value这样的键值对转换成我们想要的格式，返回的是a=1&b=2这样的字符串
            full_url += "&" + s

        if replace:
            full_url = str.format(full_url,replace)  # str.format() 方法通过字符串中的{}来识别替换字段 ，从而完成字符串的格式化

        return full_url

    @allure.step('请求')
    def creat_request_log(self,url,method,body,headers):
        print('请求日志：',url,method,body,headers)

    @allure.step('响应')
    def creat_response_log(self,status_code,text):
        print('响应日志：',status_code,text)

if __name__ == '__main__':
    # httpcase = HttpClient().send(url='http://admin-test.yueguanjia.com/logon?username=yajing.shen@yueguanjia.com&password=6c7125ad8d25d05f805d3a8cdbee7a6e7cb16b76',
    #                 method="post")
    # print('--------')
    # print(httpcase)
    clent = HttpClient()
    re = clent.send(url='http://121.37.169.128:8201/mall-member/sso/login?password=123456&username=admin',
                    method="post")
    print('--------')
    print(re)


